package com.glp.controller;

import com.glp.common.constants.GlpConstants;
import com.glp.common.resp.ApiResult;
import com.glp.common.util.MyUtil;
import com.glp.pojo.Report;
import com.glp.services.ReportService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("upload")
public class UploadController {

    @Autowired
    private ReportService reportService;

    @PostMapping("/report/baseInfo")
    public ApiResult baseInfo(@RequestBody Report report){
        if(StringUtils.isEmpty(report.getUuid())){
            return new ApiResult(10002,"uuid不能为null");
        }
        Report temp = reportService.getReportByUUid(report.getUuid());
        if(ObjectUtils.isNotEmpty(temp)){
            return new ApiResult(10004,"有重复uuid,上传失败");
        }
        report.setCreateTime(new Date());
        report.setUpdateTime(new Date());
        report.setCreateBy(GlpConstants.ANDROID_USER_ID);
        int i = reportService.addReport(report, 0);
        if(i == 1){
            return new ApiResult();
        }else{
            return new ApiResult(10001,"数据上传失败!");
        }
    }

    @PostMapping("/report/image")
    public ApiResult image(@RequestBody Report report){
        if (StringUtils.isEmpty(report.getUuid())) {
            return new ApiResult(10002,"uuid不能为null");
        }
        Report temp = reportService.getReportByUUid(report.getUuid());
        if(ObjectUtils.isEmpty(temp)){
            return new ApiResult(10003,"未找到此uuid匹配的报告信息");
        }
        report.setReportId(temp.getReportId());
        report.setUpdateTime(new Date());
        base64LoadReport(report);
        int i = reportService.modifyReport(report);
        if(i == 1){
            return new ApiResult();
        }else{
            return new ApiResult(10001,"数据上传失败!");
        }
    }

    /**
     * base64转图片 , 并存本地
     */
    private void base64LoadReport(Report report) {
        report.setJxztzp(MyUtil.Base64ToImage(report.getJxztzp()));
        report.setClmpzp(MyUtil.Base64ToImage(report.getClmpzp()));
        report.setFdjmpzp(MyUtil.Base64ToImage(report.getFdjmpzp()));
        report.setHclzzzp(MyUtil.Base64ToImage(report.getHclzzzp()));
        report.setJczp(MyUtil.Base64ToImage(report.getJczp()));
        report.setJgzp(MyUtil.Base64ToImage(report.getJgzp()));
    }
}
